<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-4">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #net_status_default="{ row }">
          <el-tag
            v-if="row.device"
            :type="row.device.net_status === 1 ? 'primary' : 'danger'"
          >
            {{
              row.device.net_status === 1
                ? t("device_manage.table.online")
                : t("device_manage.table.offline")
            }}
          </el-tag>
          <span v-else />
        </template>
        <template #active_status_default="{ row }">
          <el-tag
            v-if="row.device"
            :type="row.device.store_id ? 'primary' : 'info'"
          >
            {{
              row.device.store_id
                ? t("device_manage.table.has_active")
                : t("device_manage.table.not_active")
            }}
          </el-tag>
          <span v-else />
        </template>
        <template #device_status_default="{ row }">
          <el-tag
            v-if="row.device"
            :type="row.device.device_status == 0 ? 'primary' : 'danger'"
          >
            {{
              row.device.device_status == 0
                ? t("device_manage.table.normal")
                : t("device_manage.table.locked")
            }}
          </el-tag>
          <span v-else />
        </template>
      </AuTable>
    </div>

    <ExcelImport v-model="showImportModal" @confirm="tableRef?.refresh()" />

    <AddEditModal
      v-model="showAddModal"
      :form-data="editRow"
      @confirm="tableRef?.refresh()"
    />

    <DistributionModal
      v-model="showRedisModal"
      :form-data="selectRows"
      @confirm="tableRef?.refresh()"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { FormulaListProp } from "@/api/teaInfuser/formula";
import {
  deviceEnterDel,
  DeviceEnterProp,
  getDeviceEnterList
} from "@/api/factory/device";
import ExcelImport from "@/views/factory/deviceTerminal/deviceManage/ExcelImport.vue";
import AddEditModal from "@/views/factory/deviceTerminal/deviceManage/AddEditModal.vue";
import DistributionModal from "./DistributionModal.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { updDeviceStatus } from "@/api/teaInfuser/device";
import { FACTORY_TYPE_LIST } from "@/utils/constants";
import { businessGetList } from "@/api/factory/business";
import { useI18n } from "vue-i18n";
import { storageLocal } from "@pureadmin/utils";
import { userKey } from "@/utils/auth";
import { setDeviceTypeTrans } from "@/utils/tool";

defineOptions({
  name: "FactoryDeviceManage"
});

// region 声明ref变量集合
const { proxy } = getCurrentInstance();
const { post } = storageLocal().getItem<{
  post: number;
}>(userKey);
const { t, te } = useI18n();
const formList = ref([
  {
    type: "select",
    key: "device_type",
    label: "device_manage.form.device_type",
    placeholder: "device_manage.form.device_type_placeholder",
    valueKey: "value",
    labelKey: "label",
    emptyValues: [null, undefined],
    options: [
      { value: "", label: "device_manage.form.all_types" },
      ...FACTORY_TYPE_LIST
    ],
    defaultValue: ""
  },
  {
    type: "date",
    inType: "daterange",
    key: "time",
    label: "device_manage.form.distribution_date",
    rangSeparator: "-",
    startPlaceholder: "device_manage.form.start_date",
    endPlaceholder: "device_manage.form.end_date",
    valueFormat: "YYYY-MM-DD HH:mm:ss",
    span: 12
  },
  {
    type: "select",
    key: "device_status",
    label: "device_manage.form.device_status",
    placeholder: "device_manage.form.device_status_placeholder",
    valueKey: "value",
    labelKey: "label",
    emptyValues: [null, undefined],
    options: [
      { value: "", label: "device_manage.form.all_types" },
      { value: 0, label: "device_manage.form.normal" },
      { value: 1, label: "device_manage.form.lock" }
    ],
    defaultValue: ""
  },
  {
    type: "select",
    key: "business_id",
    label: "device_manage.form.business",
    placeholder: "device_manage.form.business_placeholder",
    valueKey: "id",
    labelKey: "brand",
    filterable: true,
    options: []
  },
  {
    type: "input",
    key: "device_id",
    label: "device_manage.form.device_code",
    placeholder: "device_manage.form.device_code_placeholder"
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    {
      field: "business_name",
      title: "device_manage.form.business_name",
      minWidth: 150,
      align: "center",
      formatter: ({ row }) => {
        return row.device ? row.device?.business_name : "";
      },
      exportMethod: ({ row }) => {
        return row.device ? row.device?.business_name : "";
      }
    },
    {
      field: "store_name",
      title: "device_manage.table.store_name",
      minWidth: 150,
      align: "center",
      formatter: ({ row }) => {
        return row.device ? row.device?.store_name : "";
      },
      exportMethod: ({ row }) => {
        return row.device ? row.device?.store_name : "";
      }
    },
    {
      field: "device_model",
      title: "device_manage.table.device_model",
      minWidth: 150,
      align: "center"
    },
    {
      field: "device_id",
      title: "device_manage.table.device_code",
      minWidth: 150,
      align: "center"
    },
    {
      field: "board_version",
      title: "device_manage.table.firmware_version",
      minWidth: 150,
      align: "center",
      formatter: ({ row }) => {
        return row.device ? row.device?.board_version : "";
      },
      exportMethod: ({ row }) => {
        return row.device ? row.device?.board_version : "";
      }
    },
    {
      field: "system_version",
      title: "device_manage.table.software_version",
      minWidth: 150,
      align: "center",
      formatter: ({ row }) => {
        return row.device ? row.device?.system_version : "";
      },
      exportMethod: ({ row }) => {
        return row.device ? row.device?.system_version : "";
      }
    },
    {
      field: "device_type",
      title: "device_manage.table.device_type",
      minWidth: 150,
      align: "center",
      formatter({ row }) {
        return setDeviceTypeTrans(row.device_model, { te, t });
      }
    },
    {
      field: "active_status",
      title: "device_manage.table.active_status",
      slots: {
        default: "active_status_default"
      },
      minWidth: 100,
      align: "center",
      exportMethod: ({ row }) => {
        return row.device
          ? row.device?.store_id
            ? t("device_manage.table.has_active")
            : t("device_manage.table.not_active")
          : t("device_manage.table.not_active");
      }
    },
    {
      field: "net_status",
      title: "device_manage.table.network_status",
      slots: {
        default: "net_status_default"
      },
      minWidth: 100,
      align: "center",
      exportMethod: ({ row }) => {
        return row.device
          ? row.device?.net_status === 1
            ? t("device_manage.table.online")
            : t("device_manage.table.offline")
          : "";
      }
    },
    {
      field: "device_status",
      title: "device_manage.table.status",
      slots: {
        default: "device_status_default"
      },
      minWidth: 100,
      align: "center",
      exportMethod: ({ row }) => {
        return row.device
          ? row.device?.device_status == 0
            ? t("device_manage.form.normal")
            : t("device_manage.form.lock")
          : "";
      }
    },
    {
      field: "activation_time",
      title: "device_manage.table.distribution_time",
      width: 170,
      align: "center",
      formatter: ({ row }) => {
        return row.device ? row.device?.activation_time : "";
      },
      exportMethod: ({ row }) => {
        return row.device ? row.device?.activation_time : "";
      }
    }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.EDIT, ACTION_TYPE.TDELETE],
  operateTools: [
    {
      key: "distribute",
      name: "table.distribute",
      disableHandle: (row: DeviceEnterProp) => row.is_activation !== 0
    }
  ],
  topTools: [
    {
      key: "excel",
      name: "device_manage.table.import_device",
      plain: true,
      seq: 12,
      onClick: () => {
        showImportModal.value = true;
      }
    },
    {
      key: "t-distribute",
      name: "table.distributeMultiple",
      plain: true,
      seq: 12,
      disableHandle: () => {
        return tableRef.value
          ? tableRef.value.getCheckboxRecords().length === 0
          : true;
      },
      onClick: () => {
        selectRows.value = [];
        selectRows.value = tableRef.value.getCheckboxRecords();
        showRedisModal.value = true;
      }
    },
    {
      key: "enable",
      name: "table.enable",
      plain: true,
      seq: 13,
      disableHandle: () => {
        return tableRef.value
          ? tableRef.value.getCheckboxRecords().length === 0
          : true;
      },
      onClick: () => {
        batchUpdateShowStatus(0);
      }
    },
    {
      key: "lock",
      name: "device_manage.form.lock",
      plain: true,
      status: "danger",
      seq: 14,
      disableHandle: () => {
        return tableRef.value
          ? tableRef.value.getCheckboxRecords().length === 0
          : true;
      },
      onClick: () => {
        batchUpdateShowStatus(1);
      }
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        const { time, ...rest } = params;
        const paramData = { ...rest };
        if (time) {
          const [activation_starttime, activation_endtime] = params.time;
          paramData["activation_starttime"] = activation_starttime;
          paramData["activation_endtime"] = activation_endtime;
        }
        return getDeviceEnterList(paramData);
      },
      param: () => formRef.value.getFormData()
    }
  }
});
const showImportModal = ref(false);

const showAddModal = ref(false);
const editRow = ref({});

const showRedisModal = ref(false);
const selectRows = ref([]);

const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合
function batchUpdateShowStatus(status: 0 | 1) {
  const data = tableRef.value.getCheckboxRecords();
  const deviceList = [],
    emptyDeviceList = [];

  let info = "";

  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    info += item.device_id;
    if (i + 1 != data.length) {
      info += "、";
    }
    if (item.device) {
      deviceList.push(item.device);
    } else {
      emptyDeviceList.push(item.device_id);
    }
  }

  if (emptyDeviceList.length) {
    proxy.$auMessageBox.alert(
      t("device_manage.table.device_not_assigned", {
        device_list: emptyDeviceList.join("、"),
        action: status
          ? t("device_manage.form.lock")
          : t("device_manage.form.active")
      }),
      t("notice.title")
    );
    return;
  }

  proxy.$auMessageBox
    .confirm(
      t("device_manage.table.confirm_action", {
        device_list: info,
        action: status
          ? t("device_manage.form.locked")
          : t("device_manage.form.active")
      }),
      t("notice.title")
    )
    .then(() => {
      const param = {
        idlist: JSON.stringify(deviceList),
        device_status: status
      };
      updDeviceStatus(param).then(res => {
        ElMessage({
          message: t("device_manage.table.action_success", {
            action: status
              ? t("device_manage.form.locked")
              : t("device_manage.form.active")
          }),
          type: "success"
        });
        tableRef.value.refresh();
      });
    });
}

function multipleDel() {
  const data = tableRef.value.getCheckboxRecords();
  let info = t("device_manage.table.delete_confirm", {
    device_list: data.map(item => item.device_id).join("、")
  });
  const devHasAcList = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].is_activation === 1) {
      devHasAcList.push(data[i].device_id);
    }
  }

  if (devHasAcList.length) {
    proxy.$auMessageBox.alert(
      t("device_manage.table.device_assigned", {
        device_list: devHasAcList.join("、")
      }),
      t("notice.title")
    );
    return;
  }

  proxy.$auMessageBox.confirm(info, t("notice.title")).then(() => {
    const param = {
      delList: JSON.stringify(data)
    };
    deviceEnterDel(param).then(res => {
      ElMessage({
        message: t("notice.delete_success"),
        type: "success"
      });
      tableRef.value.refresh();
    });
  });
}

function getBusinessList() {
  businessGetList({ size: 0 }).then(res => {
    formRef.value.setFormProps("business_id", { options: res.data });
  });
}

// endregion

// region 组件事件的集合
const search = () => {
  tableRef.value.refresh();
};

type ActionType = {
  key: ACTION_TYPE | string;
  row: FormulaListProp;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case "distribute":
      selectRows.value = [row];
      showRedisModal.value = true;
      break;
    case ACTION_TYPE.TADD:
      editRow.value = {};
      showAddModal.value = true;
      break;
    case ACTION_TYPE.EDIT:
      editRow.value = row;
      showAddModal.value = true;
      break;
    case ACTION_TYPE.TDELETE:
      multipleDel();
      break;
    default:
      break;
  }
};
// endregion

onMounted(() => {
  // 获取设备列表
  getBusinessList();

  if (post == 63 || post == 94) {
    gridOption.topTools = gridOption.topTools.filter(
      v => v.key !== "enable" && v.key !== "lock" && v.key !== "t-distribute"
    );
    gridOption.operateTools = [];

    formList.value = formList.value.filter(v => v.key !== "business_id");
  }
});
</script>
